using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

namespace AudioStudio
{
    /// <summary>
    /// Dropdown sound
    /// </summary>
    [AddComponentMenu("AudioStudio/DropdownSound")]
    public class DropdownSound : MonoBehaviour
    {
        public AudioEvent[] ValueChangeEvents;
        public AudioEvent[] PopupEvents;
        public AudioEvent[] CloseEvents;

        private bool isValueChanged = false;
        private bool isPopuped = false;
        private Dropdown c;

        void Start()
        {
            c = this.gameObject.GetComponent<Dropdown>();
            if (c != null)
            {
                c.onValueChanged.AddListener(x => PlayValueChangeSound());

                EventTrigger trigger = c.GetComponent<EventTrigger>();
                if (trigger == null)
                {
                    trigger = this.gameObject.AddComponent<EventTrigger>();
                }
                if (trigger != null)
                {
                    EventTrigger.Entry entry = new EventTrigger.Entry();
                    entry.eventID = EventTriggerType.PointerClick;

                    entry.callback.AddListener((x) => { PlayPopupSound(); });
                    trigger.triggers.Add(entry);

                    EventTrigger.Entry submit = new EventTrigger.Entry();
                    submit.eventID = EventTriggerType.Submit;

                    submit.callback.AddListener((x) => { PlayPopupSound(); });
                    trigger.triggers.Add(submit);

                    EventTrigger.Entry close = new EventTrigger.Entry();
                    close.eventID = EventTriggerType.Select;

                    close.callback.AddListener((x) => { PlayCloseSound(); });
                    trigger.triggers.Add(close);

                    EventTrigger.Entry cancel = new EventTrigger.Entry();
                    cancel.eventID = EventTriggerType.Cancel;

                    cancel.callback.AddListener((x) => { PlayCloseSound(); });
                    trigger.triggers.Add(cancel);
                }
            }
        }

        private void PlayPopupSound()
        {
            if (AkSoundEngine.IsInitialized())
            {
                AudioManager.Instance.PostEvents(null, PopupEvents);
            }
            isPopuped = true;
        }

        private void PlayValueChangeSound()
        {
            if (AkSoundEngine.IsInitialized())
            {
                AudioManager.Instance.PostEvents(null, ValueChangeEvents);
            }
            isValueChanged = true;
        }

        private void PlayCloseSound()
        {
            if (isPopuped)
            {
                if (AkSoundEngine.IsInitialized() && !isValueChanged)
                {
                    AudioManager.Instance.PostEvents(null, CloseEvents);
                }
            }
            isValueChanged = false;
            isPopuped = false;
        }
    }
}

